if( toolbox == undefined ) {
	var toolbox = {};
}

if( hq == undefined)  {
	var hq = {};
}

toolbox.delegate = function( func, obj ) {

	if( func == false ) {
		throw new Error( 'Delegate function is undefined.' );
	}
	
	if( obj == false ) {
		throw new Error( 'Delegate object is undefined.' );
	}
	
	var len = arguments.length;
	if( len > 2 ) {
		
		var params = [];
		
		for( var i=2; i<len; i++ ) {
			params[params.length] = arguments[i];
		}
		
		return function() { 
			var args = [];
			len = arguments.length;
			for( var i=0; i<len; i++ ) {
				args[args.length] = arguments[i];
			}
			
			return func.apply( obj, args.concat( params ) );
		};
		
	}
	
	return function() {
		return func.apply( obj, arguments );
	};
	
};

// do not carry over arguments from the caller of the delegated function
toolbox.delegateNPA = function( func, obj ) {
	
	if( func == false ) {
		throw new Error( 'Delegate function is undefined.' );
	}
	
	if( obj == false ) {
		throw new Error( 'Delegate object is undefined.' );
	}
	
	var len = arguments.length;
	if( len > 2 ) {
		
		var params = [];
		
		for( var i=2; i<len; i++ ) {
			params.push( arguments[i] );
		}
		
		return function() {
			return func.apply( obj, params );
		};
		
	}
	
	return function() {
		return func.apply( obj );
	};
	
};

toolbox.formVals = function(root) {
	if(typeof(jQuery) == 'undefined') { throw new Error('jQuery required'); }
	
	var res = {};
	$j(root).find('input,select').each(function() {
		var $this = $j(this);
		var myVal;

		if($this.is('input:checkbox') || $this.is('input:radio')) {
			myVal = (this.checked ? $this.val() : false);
		} else {
			myVal = $this.val();
		}
		
		if($this.attr('name').match(/^.*\[\]$/)) {
			if(!res[$this.attr('name')])	
				res[$this.attr('name')] = [];
				
			if(myVal)	
				res[$this.attr('name')].push(myVal);
		} else {
			if( myVal ) 	
				res[$this.attr( 'name' )] = myVal;
		}
	});
	
	return res;
};

toolbox.queryStr = function( params ) {

	var res = [];
	
	for( var key in params ) {
		if( typeof( params[key] ) === 'object' ) {
			if( params[key] === null ) { continue; }
			for( var i=0; params[key][i]; i++ ) {
				res[ res.length ] = key  + '=' + encodeURIComponent( params[key][i] );
			}
		} else {
			res[ res.length ] = key + '=' + encodeURIComponent( params[key] );
		}
	}
	
	return res.join( '&' );
	
};

toolbox.getExtents = function(map) {
	var bounds = map.getBounds();
        var ne = bounds.getNorthEast();
        var sw = bounds.getSouthWest();

	var extents = {
		minX : ne.lng(),
        	maxX : sw.lng(),
                minY : sw.lat(),
	        maxY : ne.lat()
	};

	return extents;	
}
